package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/***
 * Handles communication with server for client
 * @author Kim Persson
 */
public class ClientCommunication {
	
	private Socket socket;
	private PrintWriter writer;
	private BufferedReader reader;


	
	/**
	 * Default constructor
	 * @param serverIp address of server
	 * @param serverPort port to connect to
	 * @throws UnknownHostException Server can't be found
	 * @throws IOException Communication exception
	 */
	public ClientCommunication(String serverIp, int serverPort) throws UnknownHostException, IOException
	{
		socket = new Socket(serverIp,serverPort);
		socket.setKeepAlive(true);
		writer = new PrintWriter(socket.getOutputStream(), true);
		reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

	}
	
	/**
	 * Sends command string over socket
	 * @param command String command to send
	 */
	public void send(String command)
	{

		writer.println(command);
	}
	
	/**
	 * Read text from socket and return results
	 * @return results written to inputstream by server
	 */
	public String getResult()
	{
		String response ="";
		try {
			response = reader.readLine();
		} catch (IOException e) {
			System.out.println("Failed to get response");
		}
		return response;
				
	}
	
	/**
	 * Closes all connections to server
	 */
	public void disconnect()
	{
		try
		{
			writer.close();
			reader.close();
			socket.close();
		} catch (IOException e)
		{
			System.out.println("Failed to disconnect");
		} finally
		{
			if (!socket.isClosed())
			{
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			}
		}
	}

	

	
	
	

}
